<template>
  <div class="flex justify-start">
    <vxe-input v-enterNextInput class="enterNextInputFlag" v-model="age" :disabled="isDisabled" @blur="ageBlur" />
    <vxe-pulldown ref="ageUnitRef" destroy-on-close transfer>
      <template #default>
        <vxe-button v-enterNextInput class="enterNextInputFlag" icon="vxe-icon-arrow-down" :disabled="isDisabled" @click="ageUnitClickEvent">{{ageUnit.unit}}</vxe-button>
      </template>
      <template #dropdown>
        <div class="my-dropdown3">
          <vxe-table ref="dropTableRef" auto-resize :data="ageUnitData" :keyboard-config="{isArrow:true,isEnter:true}" :row-config="{isCurrent:true}" :cell-class-name="cellClassName" @cell-click="cellClick">
            <vxe-column type="seq" width="30" align="center"></vxe-column>
            <vxe-column field="unit" title="年龄单位"></vxe-column>
          </vxe-table>
        </div>
      </template>
    </vxe-pulldown>
    <vxe-input v-enterNextInput class="enterNextInputFlag" ref="secAgeRef" v-model="secAge" v-if="ageUnit.value!==6" :disabled="isDisabled" @blur="secAgeBlur" />
    <vxe-pulldown ref="secAgeUnitRef" destroy-on-close transfer v-if="ageUnit.value!==6">
      <template #default>
        <vxe-button :disabled="isDisabled">{{secAgeUnit.unit}}</vxe-button>
      </template>
    </vxe-pulldown>
  </div>
</template>
<script lang="ts" setup>
import { h } from 'vue';
import { ElNotification } from 'element-plus';
import { IsEmpty } from '@/utils/common';
import { reactive, ref, getCurrentInstance, onMounted, watch, provide } from 'vue';
import { VxePulldownInstance } from 'vxe-table';
import VXETable from 'vxe-table';
let { proxy }: any = getCurrentInstance();
const ageUnitRef = ref<VxePulldownInstance>(null);
const secAgeUnitRef = ref<VxePulldownInstance>(null);
const dropTableRef = ref(null);
let props = defineProps({
  ageObj: { type: Object as PropType<any>, default: null },
  isDisabled: { type: Boolean, default: false }
});

let isShowTips = ref(false);
let textTips = ref('正在打印中...');
defineExpose({});

//#region  自定义指令
// 自定义指令
const enterNextInput: ObjectDirective<HTMLElement> = {
  mounted(el) {
    el.addEventListener('keypress', (e) => {
      let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode;
      if (charcode == 13) {
        const doms: any = document.getElementsByClassName('enterNextInputFlag');
        let list = [];
        for (let i = 0; i < doms.length; i++) {
          let node = doms[i].childNodes;
          if (node.length > 0) {
            node.forEach((v) => {
              if ((v.nodeName == 'TEXTAREA' || v.nodeName == 'INPUT') && !v.disabled) {
                list.push(v);
              }
            });
          }
        }
        for (let j = 0; j <= list.length; j++) {
          if (list[j] == document.activeElement) {
            if (j == list.length - 1) {
              return;
            }
            list[j + 1].focus();
            return;
          }
        }
      }
    });
  }
};

// 使用自定义指令
proxy.$.directives = { enterNextInput: enterNextInput };
//#endregion

const baseUnitArray = [
  { value: 1, unit: '岁' },
  { value: 2, unit: '月' },
  { value: 3, unit: '天' },
  { value: 4, unit: '时' },
  { value: 5, unit: '分' },
  { value: 6, unit: '秒' }
];
let ageUnitData = ref(baseUnitArray);
let age = ref(null);
let ageUnit = reactive({ value: 1, unit: '岁' });
const secAgeRef = ref(null);
let secAge = ref(null);
let secAgeUnit = reactive({ value: 2, unit: '月' });
watch(
  () => props.ageObj,
  (n, o) => {
    if (n && !IsEmpty(n)) {
      if (n.ageUnit && !IsEmpty(n.ageUnit)) {
        let au = baseUnitArray.find((item: any) => item.unit == n.ageUnit);
        Object.assign(ageUnit, au);
      }
      if (!n.ageUnit || IsEmpty(n.ageUnit)) {
        Object.assign(ageUnit, { value: 1, unit: '岁' });
      }
      if (n.secAgeUnit && !IsEmpty(n.secAgeUnit)) {
        Object.assign(secAgeUnit, n.secAgeUnit);
      }
      if (!n.secAgeUnit || IsEmpty(n.secAgeUnit)) {
        let au = baseUnitArray.find((item: any) => item.value == ageUnit.value + 1);
        Object.assign(secAgeUnit, au);
      }
      if (!IsEmpty(n.age)) {
        age.value = n.age;
      }
      if (IsEmpty(n.age)) {
        age.value = null;
      }
      if (!IsEmpty(n.secAge)) {
        secAge.value = n.secAge;
      }
      if (IsEmpty(n.secAge)) {
        secAge.value = null;
      }
    }
  },
  { immediate: true, deep: true }
);

/**
 * 事件拦截器
 *
 */
VXETable.interceptor.add('event.keydown', (params, event) => {
  if (params.$event.keyCode === 13) {
    if (ageUnitRef.value?.isPanelVisible()) {
      const row = dropTableRef.value?.getCurrentRecord();
      Object.assign(ageUnit, row);
      if (ageUnitRef.value) {
        ageUnitRef.value?.hidePanel();
      }
      if (secAgeRef.value) {
        secAgeRef.value?.focus();
      }
      if (row.value < baseUnitArray.length) {
        Object.assign(secAgeUnit, baseUnitArray[row.value]);
      }
      if (row.value === baseUnitArray.length) {
        Object.assign(secAgeUnit, baseUnitArray[row.value]);
        Object.assign(secAgeUnit, { value: -1, unit: '' });
        secAge.value = null;
      }
      ageUnitChange({});
      return false;
    }
  }
});

/**
 * 选择年龄单位
 * 年龄单位选择
 */
async function ageUnitClickEvent() {
  if (ageUnitRef.value) {
    await ageUnitRef.value?.togglePanel();
    proxy.$nextTick(() => {
      if (ageUnitRef.value?.isPanelVisible()) {
        dropTableRef.value?.setCurrentRow(ageUnitData.value[0]);
        dropTableRef.value?.focus();
      }
    });
  }
}

/**
 * 选择年龄单位
 * 二级年龄单位选择
 */
function secAgeUnitClickEvent() {
  if (secAgeUnitRef.value) {
    secAgeUnitRef.value?.togglePanel();
  }
}

/**
 * 单元格样式
 */
function cellClassName() {
  return 'padding-lr-xs';
}

/**
 * 单元格点击事件
 */
function cellClick({ row }) {
  if (ageUnitRef.value) {
    ageUnitRef.value?.togglePanel();
  }
  Object.assign(ageUnit, row);
  if (secAgeRef.value) {
    let au = baseUnitArray.find((item: any) => item.value == ageUnit.value + 1);
    Object.assign(secAgeUnit, au);
    secAgeRef.value?.focus();
  }
}

/**
 * 第一年龄失去焦点
 * @e 事件源
 */
function ageBlur(e) {
  const ageObj = {
    age: age.value,
    ageUnit: ageUnit.unit,
    secAge: secAge.value,
    secAgeUnit: secAgeUnit.unit
  };
  submitChange(ageObj);
}

/**
 * 第二年龄失去焦点
 * @e 事件源
 */
function secAgeBlur(e) {
  const ageObj = {
    age: age.value,
    ageUnit: ageUnit.unit,
    secAge: secAge.value,
    secAgeUnit: secAgeUnit.unit
  };
  submitChange(ageObj);
}

/**
 * 年龄单位选择改变
 * @e 事件源
 */
function ageUnitChange(e) {
  //todo
  const ageObj = {
    age: age.value,
    ageUnit: ageUnit.unit,
    secAge: secAge.value,
    secAgeUnit: secAgeUnit.unit
  };
  submitChange(ageObj);
}

/**
 * 年龄改变Emit 回调函数
 * @ageObj 当前年龄数据
 */
function submitChange(ageObj) {
  proxy.$emit('ageChange', ageObj);
}

const open1 = () => {
  ElNotification({
    title: '提示',
    message: h('i', { style: 'color: teal' }, '正在打印...'),
    type: 'success',
    duration: 0,
    showClose: false
  });
};
</script>
<style lang="scss" scoped>
.my-dropdown3 {
  width: 200px;
  background-color: #fff;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}
</style>
